package com.ljy.kotlindemo

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.*
import java.lang.Exception
import java.util.concurrent.TimeUnit

class MainActivity : AppCompatActivity() {

    val handler: Handler = Handler(Looper.getMainLooper())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val map=HashMap<String,Any>()
        map.put("appCode","ZJB")
        demoRetrofit(map)
        demoRetrofit2(map)
    }

    /**
     * 4.请求数据
     */
    private fun demoRetrofit(map: HashMap<String, Any>) {
        gitHubServiceApi.getUser("api/v1/agreement/appAgreement/getlastagreement",map).enqueue(object : Callback<UserGit> {
            override fun onResponse(call: Call<UserGit>, response: Response<UserGit>) {
                handler.post {
                    response.body()?.let(::showUser) ?: showError(NullPointerException())
                }
            }

            override fun onFailure(call: Call<UserGit>, t: Throwable) {
                handler.post {
                    showError(t)
                }
            }

        })
    }

    /**
     * 5. 改造成协程方式
     */
//5.1 CallAdapter 的方式
    private fun demoRetrofit2(map: HashMap<String, Any>) {
        GlobalScope.launch(Dispatchers.Main) {
            try {
                showUser(gitHubServiceApi2.getUser("api/v1/agreement/appAgreement/getlastagreement",map).await())
            } catch (e: Exception) {
                showError(e)
            }
        }
    }

    private fun showUser(userGit: UserGit) {
        Log.d("LJY", "user=$userGit")
    }


    private fun showError(t: Throwable) {
        t.printStackTrace()
        Log.e("LJY", t.message.toString())
    }
}

/**
 * 1. userBean
 */
data class UserGit(val status: Int, val message: String, val currentTime: String,val data: Data) {
    override fun toString(): String {
        return "UserGit(status=$status, message='$message', currentTime='$currentTime', data=$data)"
    }
}

data class Data(val id:Int, val appCode:String,val agreementVerCode:Int,val agreementVerDesc:String){
    override fun toString(): String {
        return "Data(id=$id, appCode='$appCode', agreementVerCode=$agreementVerCode, agreementVerDesc='$agreementVerDesc')"
    }
}

/**
 * 2. 接口api
 */
interface GitHubServiceApi {
    @GET()
    fun getUser(@Url url:String, @QueryMap options: HashMap<String, Any>): Call<UserGit>
}

//callAdapter方式：这个方式的本质是让接口的方法返回一个协程的 Job， Deferred 是 Job 的子接口
interface GitHubServiceApi2 {
    @GET()
    fun getUser(@Url url:String, @QueryMap options: HashMap<String, Any>): Deferred<UserGit>
}

/**
 * 3. retrofit初始化
 */
val gitHubServiceApi by lazy {
    val retrofit = retrofit2.Retrofit.Builder()
        .baseUrl("https://app-api.runpozx.com/")
        .client(getOkHttpClient())
        .addConverterFactory(GsonConverterFactory.create())
        .build()
    retrofit.create(GitHubServiceApi::class.java)
}

//callAdapter方式
val gitHubServiceApi2 by lazy {
    val retrofit = Retrofit.Builder()
        .baseUrl("https://app-api.runpozx.com/")
        .client(getOkHttpClient())
        .addConverterFactory(GsonConverterFactory.create())
        //添加对 Deferred 的支持
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .build()
    retrofit.create(GitHubServiceApi2::class.java)
}

/**
 * OkHttpClient配置
 */
fun getOkHttpClient(): OkHttpClient? {
    var builder = OkHttpClient.Builder()

    builder.connectTimeout(10, TimeUnit.SECONDS) //设置连接超时
        .readTimeout(30, TimeUnit.SECONDS) //设置读超时
        .writeTimeout(30, TimeUnit.SECONDS)//设置写超时
        .sslSocketFactory(TrustAllCerts.createSSLSocketFactory()) // 信任证书，便于调试时抓包
        .hostnameVerifier(TrustAllCerts.TrustAllHostnameVerifier())
    return builder.build()
}

